/*
 * Copyright 2016-2017 lei.xu<xulei2008xulei@163.com>.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.san21go.jfinfunc.financ.norm;

import org.san21go.jfinfunc.AbstractFunction;
import org.san21go.jfinfunc.FinFuncRuntimeException;
import org.san21go.jfinfunc.math.covariance.COVARIANCES;
import org.san21go.jfinfunc.math.var.VARS;

/**
 * 表示投资的系统性风险，反映了策略对大盘变化的敏感性。<br/>
 * Beta值 解释<br/>
 * 
 * β<0 投资组合和基准的走向通常反方向，如空头头寸类<br/>
 * β=0 投资组合和基准的走向没有相关性，如固定收益类<br/>
 * 0<β<1 投资组合和基准的走向相同，但是比基准的移动幅度更小<br/>
 * β=1 投资组合和基准的走向相同，并且和基准的移动幅度贴近<br/>
 * β>1 投资组合和基准的走向相同，但是比基准的移动幅度更大<br/>
 * 
 * @author xulei
 *
 */
public class Beta extends AbstractFunction<Double> {
	/**
	 * 策略每日收益
	 */
	private double[] yieldRates;
	/**
	 * 基准每日收益
	 */
	private double[] baseRates;

	public Beta(double[] yieldRates, double[] baseRates) {
		super();
		this.yieldRates = yieldRates;
		this.baseRates = baseRates;
	}

	@Override
	public Double evaluate() {
		if (yieldRates == null || baseRates == null || yieldRates.length == 0 || baseRates.length == 0) {
			throw new FinFuncRuntimeException("参数错误");
		}
		if (baseRates.length != yieldRates.length) {
			throw new FinFuncRuntimeException("参数错误");
		}

		double covs = new COVARIANCES(yieldRates, baseRates).evaluate();
		double vars = new VARS(baseRates).evaluate();

		if (Double.compare(covs, 0) == 0) {
			return 0D;
		}
		return covs / vars;
	}

}
